package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.dao.po.UserInfo;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.text.MessageFormat;
import java.util.List;

@Slf4j
@RestController
@CrossOrigin
public class HelloController {

    @Autowired
    private UserService userService;

    @Value("${app.version}")
    private String version;

    @Value("${username:张三}")
    private String userName;

    @Value("${access_level:0}")
    private String accessLevel;

    @GetMapping("/app-version")
    public String getVersion() {
        return this.version;
    }

    @GetMapping("/hello")
    public String hello(HttpServletRequest request) {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            String pattern = "host:{0}, address:{1}, hostName:{2}, 请求来自:{3}";
            String ip = getIp(request);
            String message = MessageFormat.format(pattern, localHost, localHost.getHostAddress(), localHost.getHostName(), ip);
            System.out.println("message:" + message);
            return message;
        } catch (Exception e) {
            System.out.println("获取请求信息失败" + e);
            return "获取请求信息失败";
        }
    }


    public String getIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress.split(",")[0];
    }

    @GetMapping("/find-user")
    public List<UserInfo> findUser() {
        List<UserInfo> list = userService.queryUserInfo();
        log.info("userList:" + list);
        return list;
    }

    @GetMapping("/get-value")
    public String getValue(){
        return this.accessLevel + "::" + this.userName;
    }
}
